package com.youyoulong.framework.auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.youyoulong.framework.auth.service.IFrameUserService;
import com.youyoulong.framework.auth.vo.FrameUser;

public class FrameworkAuthorizingRealm extends AuthorizingRealm {

	@Autowired
	private IFrameUserService frameUserService;

	/**
	 * 验证当前登录的Subject
	 * 
	 * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		/* 这里编写登陆认证代码 */
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		FrameUser user = new FrameUser();
		user.setUserName(token.getUsername());
		try {
			user = frameUserService.getUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(token.getPassword()==null){
			return null;
		}else{
			if(new String(token.getPassword()).equals(user.getPassword())){
				return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), getName());
			}else{
				return null;
			}
		}

		

		/*
		 * //令牌——基于用户名和密码的令牌 UsernamePasswordToken token =
		 * (UsernamePasswordToken) authcToken; //令牌中可以取出用户名密码 String accountName
		 * = token.getUsername();
		 * 
		 * // 此处无需比对，比对的逻辑Shiro会做，我们只需返回一个和令牌相关的正确的验证信息，因此在随后的登录页面上只有admin/
		 * admin123才能通过验证 return new
		 * SimpleAuthenticationInfo("admin","admin123",getName());
		 */
	}

	/**
	 * 将一些数据放到ShiroSession中,以便于其它地方使用
	 * 
	 * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
	 */
	private void setSession(Object key, Object value) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
			if (null != session) {
				session.setAttribute(key, value);
			}
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

}
